<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;

use cmf\controller\RestUserBaseController;
use cmf\model\UserModel;
use model\GoodsModel;
use model\OrderModel;
use plugins\helper\Date;
use think\db\Query;
use think\facade\Db;

class OrderController extends RestUserBaseController
{
    protected $orderModel;
    public $flag;

    public function initialize()
    {
        parent::initialize();
        $this->orderModel = new OrderModel();
    }

    /**
     * 创建订单
     * @throws \Exception
     */
    public function createOrder()
    {
        $data = $this->request->post();
        $this->flag = $data['flag'];
        $goods = GoodsModel::where(['id' => $data['goods_id'], 'status' => 1, 'check' => 1])->find()->toArray();
        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods['stock'] - $data['goods_num'] <= 0) {
            return $this->error('商品数量不足');
        }

        $insertData = [
            'order_price' => $data['goods_num'] * $goods['price'],
            'user_id' => $this->userId,
            'merch_id' => $goods['merch_id'],
            'order_type' => 1,
            'create_time' => date('Y-m-d h:i:s', time()),
            'goods_id' => $data['goods_id'],
            'goods_title' => $goods['title'],
            'goods_num' => $data['goods_num'],
            'goods_price' => $goods['price'],
            'thumb' => $goods['thumb'],
            'source' => 0,
            'status' => 0,
        ];
        if ($this->flag == false) {
            return $this->success('成功', $insertData);
        }
        $insertData['order_no'] = OrderModel::getOrderNo();
        $order_id = $this->orderModel->insertGetId($insertData);
        Db::name('goods')
            ->where('id', $data['goods_id'])
            ->Inc('sales_num', 1)->Dec('stock', 1)->update();

        return $this->success('成功', ['id' => $order_id]);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = $this->request->get('id');
        if (empty($id)) {
            return $this->error('数据错误');
        }
        $order = $this->orderModel->where(['id' => $id])->find();
        if (empty($order['receive_code'])) {
            $order['receive_code'] = $this->orderModel->getReceiveCode();
            Db::name('order')->where('id', $id)->update(['receive_code' => $order['receive_code']]);
        }
        $order = $this->orderModel->decode($order);
        return $this->success('成功', $order);
    }


    /**
     * 支付订单
     */
    public function payOrder()
    {

        $order_id = $this->request->post('order_id');
        $order = OrderModel::where(['id' => $order_id])->find();
        if (empty($order)) {
            return $this->error('订单不存在');
        }

        if ($order['status'] != 0) {
            return $this->error('订单状态错误,无法支付');
        }
        $user = UserModel::where(['id' => $this->userId])->find()->toArray();
        $balance = $user['balance'];

        if ($balance < $order['order_price']) {
            return $this->error('余额不足,无法支付');
        }
        Db::startTrans();
        try {
            Db::name('user')
                ->where('id', $this->userId)
                ->Dec('balance', $order['order_price'])->update();

            OrderModel::where(['id' => $order_id])->update(['status' => 1, 'expired_time' => Date::nowLater(7), 'pay_time' => Date::now()]);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('订单状态错误,无法支付');
        }

        $this->userId = Db::name('user')
            ->where('id', $this->userId)->find();

        return $this->success('支付成功');

    }


    /**
     * 列表
     * @throws \think\db\exception\DbException
     */
    public function list()
    {
        $param = $this->request->get();
        $limit = empty($param['limit']) ? 10 : $param['limit'];
        $page = isset($param['page']) ? $param['page'] : false;
        if ($page <= 1) {
            $offset = 0;
        } else {
            $offset = $limit * ($page - 1);
        }

        $orderList = Db::name('order')
            ->where(function (Query $query) use ($param) {
                if ($param['status'] != 0) {
                    if ($param['status'] == 4) {
                        $query->where('refund_status', 'in', [1, 2]);
                    } else {
                        $query->where('status', $param['status'] - 1);
                    }
                }

            })->where('user_id', $this->userId)->limit($offset, $limit)->order('id DESC')->select()->toArray();

        foreach ($orderList as &$item) {
            $item = $this->orderModel->decode($item);
        }
        return $this->success('成功', $orderList);
    }


    /**
     * 取消订单
     */
    public function cancel()
    {

        $id = $this->request->get('id');
        if (empty($id)) {
            return $this->error('订单不存在');
        }
        $order = OrderModel::where(['id' => $id, 'user_id' => $this->userId])->find();
        if (empty($order)) {
            return $this->error('订单不存在');
        }

        Db::startTrans();
        try {
            Db::name('user')
                ->where('id', $this->userId)
                ->Inc('balance', $order['order_price'])->update();

            Db::name('order')
                ->where('id', $id)
                ->update(['status' => -1, 'close_time' => Date::now(), 'close_reson' => '用户手动取消']);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('订单状态错误,无法支付');
        }

        $this->userId = Db::name('user')
            ->where('id', $this->userId)->find();

        return $this->success('取消成功');

    }

    /**
     * 收银订单
     */
    public function Cashier()
    {
        $data = $this->request->post();

        $insertData = [
            'order_price' => $data['price'],
            'user_id' => $this->userId,
            'merch_id' => $data['merch_id'],
            'order_type' => 2,
            'create_time' => date('Y-m-d h:i:s', time()),
            'goods_id' => 0,
            'goods_title' => '收银订单',
            'goods_num' => 1,
            'goods_price' => $data['price'],
            'thumb' => '',
            'source' => 0,
            'status' => 2,
        ];

        $insertData['order_no'] = OrderModel::getOrderNo();

        Db::startTrans();
        try {
            $order_id = $this->orderModel->insertGetId($insertData);
            Db::name('merch')
                ->where('id', 1)
                ->Inc('balance', $data['price'])->update();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('订单状态错误,无法创建订单');
        }
        return $this->success('成功', ['id' => $order_id]);
    }


    /**
     * 申请维权
     */
    public function refund()
    {
        $id = $this->request->post('id');
        $order = OrderModel::where(['id' => $id])->find()->toArray();
        if ($order['refund_status'] != 0) {
            return $this->error('订单状态错误,无法申请');
        }
        if ($order['status'] != 1) {
            return $this->error('订单状态错误,无法申请');
        }

        Db::startTrans();
        try {
            Db::name('user')
                ->where('id', $this->userId)
                ->Inc('balance', $order['order_price'])->update();

            Db::name('order')
                ->where('id', $id)
                ->update(['status' => -1, 'close_time' => Date::now(), 'close_reson' => '用户维权','refund_status'=>2]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('订单状态错误,无法创建订单');
        }
        return $this->success('成功', ['id' => $id]);

    }


}
